package com.iias.common.util.rect;

import java.lang.reflect.Field;

/**
 * 字段操作工具类
 */
public class ZbFields {


    /**
     * 获取字段值
     * @param o   作用对象
     * @param join 分割符号
     * @param fields 字段名称
     * @return
     */
    public static String getFieldValues(Object o,String join,String ...fields){
        StringBuffer buffer = new StringBuffer();
        Class<?> aClass = o.getClass();
        join = join == null?"":join;
        for (int i = 0; i < fields.length; i++) {
                Field fieldSupper = getFieldSupper(fields[i], aClass);
                if (fieldSupper == null) throw new RuntimeException("字段不存在");
                fieldSupper.setAccessible(true);
                Object val = null;
            try {
                val = fieldSupper.get(o);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            if (val != null){
                buffer.append(val.toString());
            }else {
                buffer.append("null");
            }
            buffer.append(join);
        }

        return buffer.toString().substring(0,buffer.length()-join.length());
    }


    /**
     * 获取包括父类在内的指定字段
     * @param fieldName 字段名称
     * @param clazz 对应的class 文件
     * @return
     */
    public static Field getFieldSupper(String fieldName,Class clazz){
        Field declaredField = null;
        try {
            declaredField =  clazz.getDeclaredField(fieldName);
            if (declaredField!=null)return declaredField;
        } catch (NoSuchFieldException e) {}
        if (declaredField == null)
        try {
             declaredField = clazz.getField(fieldName);
            if (declaredField!=null)return declaredField;
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        clazz = clazz.getSuperclass();
        if (clazz == null)return null;
        return getFieldSupper(fieldName,clazz);
    }
}
